package com.front.servlets;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import books.borrowing.EJBFacade;
import books.borrowing.bo.IBookBorrowingBo;
import books.borrowing.bo.ISubscriberBo;
import books.borrowing.entity.BookBorrowingEntity;
import books.borrowing.entity.SubscriberEntity;
import books.storage.service.BookDto;

public class Login extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -3039777008866529780L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher("/index.jsp");
		dispatcher.forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession(true);

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// Try to connect
		ISubscriberBo _serviceSubscriber = EJBFacade.getSubscriberBo();
		SubscriberEntity user = null;
		try {
			user = _serviceSubscriber.connect(username, password);
		} catch(Exception e) {
			
		}
		session.setAttribute("user", user);
		if(user==null) {
			session.setAttribute("try_connect", "CONNECTION_FAILED");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher("/index.jsp");
			dispatcher.forward(request, response);
		} else {
			Login.actualizeUerRents(session, user.getLogin());
			response.sendRedirect("/ELibrary/catalog");
		}

	}
	
	public static void actualizeUerRents(HttpSession session, String userLogin) {
		// Get user rents
		if(userLogin != null) {
			IBookBorrowingBo bo = EJBFacade.getBookBorrowingBo();
			List<BookBorrowingEntity> booksBorrowed = bo.findSubscriberRents(userLogin);
			session.setAttribute("books_borrowed", booksBorrowed);
		}
	}
}